<?php
namespace app\dlc\controller;

use think\Session;
use think\Db;
class indexController extends BaseController
{
    public $datas;
	//CMS总入口
    public function index()
    {
        $role_auth = model('role')->where(array('role_id' => $this->role_id))->value('auth');
        $role_oath1 = model('role_oath')->where("oath_id in (".$role_auth.") and module='Dlc' and parent_id=0")->field("oath_id,name,url,icon")->order(array('order' => 'desc'))->select();
        if($role_oath1) {
            $role_oath2 = model('role_oath')
						->where("oath_id in (".$role_auth.") and module='Dlc' and parent_id<>0 and is_menu=1")
						->field("oath_id,name,url,parent_id")
						->order(array('order' => 'desc'))
						->select();
            if($role_oath2) {
                foreach ($role_oath2 as $k => $v) {
                    $role_oath2[$k]['url'] = url('Dlc/'.$v['url']);
                }
            }
            $auth  = model('set')->find();
        }
        foreach ($role_oath2 as $k => $v) {
        }
        $role_oath1['0']['url'] = 'main2';
        $array = array($role_oath1[0]);
        $this->assign('auth',$auth);
        $this->assign('roleid',Session::get('CMS.user.roleid'));
        $this->assign('main',$array?:array());
        $this->assign('role_oath1',$role_oath1?:array());
        $this->assign('role_oath2',$role_oath2?:array());
		//var_dump(session('CMS.user'));
        return $this->fetch();
    }


	public function main()
    {
        //设置面包导航，主加载器请配置
        $bread = array(
            '0' => array(
                'name' => '主控面板',
                'url' => url('dlc/Index/main'),
            ),
        );
        $breadhtml = $this->getBread($bread);
        $this->assign('breadhtml', $breadhtml);
        die;
        $type = input('type','','trim') ? : 1;//查询类型【1：今日 2：本周 3：本月】
        //本月起始
        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $mapThismonth['ctime'] = array('between', array($beginThismonth, $endThismonth));
        //今日时间
        $todaystime = strtotime(date('Y-m-d',time()));
        $todayetime = strtotime(date('Y-m-d'.time()).' 23:59:59');

        //新用户数量
        $newUserNum    = Db::name('user')->where(['ctime'=>array('between', array($todaystime, $todayetime))])->count();
        //设备总数量
        $deviceNum     = Db::name('device')->count();
        //今日总营收
        $todayMoney    = Db::name('order')->where(['status'=>2,'pay_time'=>['between',[$todaystime, $todayetime]]])->sum('real_money') ? : '0.00';
        //场地总数量
        $siteNum       = Db::name('site')->count();
        //代理商总数量
        $agentNum      = Db::name('agent')->count();
        //今日订单总数量
        $todayOrderNum = Db::name('order')->where(['pay_time'=>['between',[$todaystime, $todayetime]]])->count();
        //总用户数量
        $userNum       = Db::name('user')->count();

        if($type ==1){
            //今日数据
            $s_start  = strtotime(date('Y-m-d',time()));
            $s_end    = $s_start;
        }elseif($type ==2){
            //本周数据
            $s_start  =  mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"));
            $s_end    =  mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));
        }else{
            //本月数据
            $s_start  = mktime(0,0,0,date('m'),1,date('Y'));
            $s_end    = mktime(23,59,59,date('m'),date('t'),date('Y'));
        }


        if($s_start && $s_end) {
            $where['ctime'] = ['between',[$s_start,$s_end+60*60*24]];
        }
        $date = [];
        if($type ==1){
            $s_end = $s_start +60*60*23;
            for ($i = $s_start; $i <= $s_end; $i+= 3600) {
                $date[] = date('Y-m-d H',$i);
            }
            $field = "sum(real_money) as amount,count(*) as order_num,FROM_UNIXTIME(ctime,'%Y-%m-%d %H') AS curdate";
        }else{
            for ($i = $s_start; $i <= $s_end; $i+= 3600 *24) {
                $date[] = date('Y-m-d',$i);
            }
            $field = "sum(real_money) as amount,count(*) as order_num,FROM_UNIXTIME(ctime,'%Y-%m-%d') AS curdate";
        }

        $where['status'] = 2;
        $data = Db::name('order')
            ->field($field)
            ->where($where)->group('curdate')->select();
//        print_r(Db::name('order')->getLastSql());

        if ($data) {
            $name = ['订单金额','订单数量'];
//            $device_map = new DeviceMap($name,$date);
            $this->operationData($name,$date);
            // print_r($device_map);
            foreach ($data as $key => $val) {
                $this->bindOrderPrice($val);
                $this->bindOrderSum($val);
            }
            $item = $this->sortData();

        }
//        print_r($item);die;
        $this->assign('name',json_encode($name));
        $this->assign('date',json_encode($date));
        $this->assign('item',json_encode($item));
        $this->assign('type',$type);
        $this->assign('newUserNum',$newUserNum);
        $this->assign('deviceNum',$deviceNum);
        $this->assign('todayMoney',$todayMoney);
        $this->assign('siteNum',$siteNum);
        $this->assign('agentNum',$agentNum);
        $this->assign('todayOrderNum',$todayOrderNum);
        $this->assign('userNum',$userNum);
        echo $this->fetch();
	}

    public function operationData($name,$data){
        foreach ($name as $key => $val) {
            $this->datas[$key]['name'] = $val;
            $this->datas[$key]['type'] = 'line';
        }
        foreach ($data as $key => $val ) {
            foreach ($this->datas as $k => $v) {
                $this->datas[$k]['data'][$val] = 0;
            }
        }
    }

    // 绑定订单金额
    public function bindOrderPrice($data)
    {
        $temp = $this->datas[0]['data'];
//        print_r(123);
//        print_r($temp);die;
        foreach ($temp as $key => $val) {
            if ($key == $data['curdate']) {
                $temp[$key] += $data['amount'];
            }
        }
        $this->datas[0]['data'] = $temp;
    }

    // 绑定订单的数量
    public function bindOrderSum($data)
    {
        $temp = $this->datas[1]['data'];
        foreach ($temp as $key => $val) {
            if ($key == $data['curdate']) {
                $temp[$key] += $data['order_num'];
            }
        }
        $this->datas[1]['data'] = $temp;
    }

    public function sortData()
    {
        foreach ($this->datas as $k => $v) {
            $data = $v['data'];
            $newData = [];
            foreach ($data as $item) {
                $newData[] = $item;
            }
            $this->datas[$k]['data'] = $newData;
        }
        return $this->datas;
    }

    //CMS后台图片浏览器
    public function appImgviewer()
    {
        $ids = input('ids');
        $type = input('type')?:0;
        if($type) {
            $imgs = [];
            if(strpos($ids,",")) {
                $imgs = explode(",",$ids);
            } else {
                $imgs = [$ids];
            }
            $cache = $imgs;
        } else {
            $m = Db::name('upload');
            $map['id'] = array('in',$ids);
            // var_dump($map['id']);
            $cache = $m->where($map)->select();

        }
        // var_dump($ids);
        $this->assign('type',$type);
        $this->assign('cache', $cache);
        return($this->fetch('appImgviewer'));
    }


	//修改用户密码
	public function modifypass(){
		//设置面包导航，主加载器请配置
        $bread = array(
            '0' => array(
                'name' => '修改密码',
                'url' => url('dlc/Index/modifypass'),
            ),
        );
		$this->assign('breadhtml', $this->getBread($bread));
		//处理POST提交
		$data = I('post.');
        if ($data) {
            if (!is_string($data['password'])){
                $info['status'] = 0;
                $info['msg'] = '请输入正确数据！';
                $this->ajaxReturn($info);
            }
            $data['password'] = md5($data['password']);
            $re = $m->where('id='.$data['id'])->update($data);
            if (FALSE !== $re) {
                $info['status'] = 1;
                $info['msg'] = '设置成功！';
            } else {
                $info['status'] = 0;
                $info['msg'] = '设置失败！';
            }
            $this->ajaxReturn($info);
        }
		echo ($this->fetch('modifypass'));
	}


    //删除管理员
    public function authname()
    {
        $id = input('id');
        if(empty($id)){
            $info['status'] =  0;
            $info['msg']    = 'ID不能为空';
            return($info);
        }
        $result = Db::name('admin')->where(['id'=>['in',$id]])->delete();
        if($result !== false){
            $info['status'] = 1;
            $info['msg']    = '删除成功';
        }else{
            $info['status'] = 0;
            $info['msg']    = '删除失败';
        }
        return($info);
    }

    public function editpassword(){
        if (request()->isPost()) {
            $password = trim(md5(input('password')));
            $newpass = trim(md5(input('newpass')));
            $rnewpass = trim(md5(input('rnewpass')));
            $id = input('id');

            $check = db('admin')->where(['id'=>$id])->find();
            // _return('0','ooo',$check);
            if ($password !== $check['password']) {
                return(['code'=>0,'msg'=>'原密码错误']);
            }
            if ($newpass == $password) {
                return(['code'=>0,'msg'=>'新密码不能与旧密码相同']);
            }
            if($rnewpass !== $newpass){
                return(['code'=>0,'msg'=>'新密码与确认密码不一致']);
            }

            $data['password'] = $newpass;

            if ($res = db('admin')->where(['id'=>$id])->update($data)) {

                return(['code'=>1,'msg'=>'修改成功,请重新登录']);
            }
        }
    }
}
